import requests, json
from requests.packages.urllib3.exceptions import InsecureRequestWarning

# 禁用安全请求警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


class syncRequest(requests.Session):
    """syncAPI对象"""

    doc = "https://docs.synclabs.so/api-reference/endpoint/animate/post-animate"
    host = "https://api.synclabs.so"

    # key = "83076839-1866-4e7f-a153-04d258a12a10"  # 谭
    # key = "3e1b5512-939b-4cff-9ea9-6086f9c41dea" # 刘洋
    # key = "268b4a26-f6ae-455c-8040-f0c368375678"
    # key = "59b7cbca-f2d7-4557-be8e-c087876a90cd"
    # key = "0188b1b7-7a30-4db6-a225-050320e9d0e4"
    # key = "9b575c0f-21b8-4102-8baa-bad5a2f9bf74"

    key = "1ec49695-1c76-4c14-bd4c-a7527d73ac8a"  # VIP

    def do_get(self, url="", headers=None, params=None, data=None):
        url = self.host + url
        try:
            r = self.get(url, headers=headers, params=params, data=data, verify=False)
            return r.json()  # if r and r.status_code == 200 else {"err": r.text}
        except BaseException as err:
            return {"err": err}

    def do_post(self, url="", headers=None, params=None, data=None, json=None):
        url = self.host + url
        try:
            r = self.post(
                url, headers=headers, params=params, data=data, json=json, verify=False
            )
            return (
                r.json() if r and r.status_code in [200, 201, 403] else {"err": r.text}
            )
        except BaseException as err:
            return {"err": err}

    def hasHeader(self):
        header = {
            "x-api-key": self.key,
            "Content-Type": "application/json",
        }
        return header

    def listLipsync(self, tid=""):
        """lipsync 唇同步"""
        url = f"/lipsync/{tid}"
        header = self.hasHeader()
        res = self.do_get(url, headers=header)
        return res

    def postLipsync(self, audio, video, synergize=True, maxCredits=None):
        """lipsync 唇同步"""
        url = "/lipsync"
        header = self.hasHeader()
        data = {
            "audioUrl": audio,
            "videoUrl": video,
            "synergize": synergize,
            "maxCredits": maxCredits,
            "model": "sync-1.6.0",
            "webhookUrl": "https://lease.3vppt.com/rebot/dosync/",
        }
        res = self.do_post(url, headers=header, json=data)
        return res

    def postAnimate(self, video, text, guid, maxCredits=123):
        """animate 将文本转换为音频，并将其与视频的嘴唇动作同步"""
        url = "/animate"
        header = self.hasHeader()
        data = {
            "videoUrl": video,
            "transcript": text,
            "voiceId": guid,
            "maxCredits": maxCredits,
            "model": "sync-1.6.0",
            "webhookUrl": "https://lease.3vppt.com/rebot/dosync/",
        }
        res = self.do_post(url, headers=header, json=data)
        return res
